<template>
    <div class="xtx-pagination" v-if="total">
        <a href="javascript:;" :class="{ disabled: currPage === 1 }" @click="changePage(currPage - 1)">上一页</a>
        <span v-if="pager.start > 1">...</span>
        <a href="javascript:;" :class="{ active: currPage === item }" v-for="item in pager.btnArr"
            @click="changePage(item)">{{ item }}</a>
        <span v-if="pager.end < pager.pageCount">...</span>
        <a href="javascript:;" :class="{ disabled: currPage === pager.pageCount }"
            @click="changePage(currPage + 1)">下一页</a>
    </div>
</template>
<script>
export default {
    name: 'XtxPagination'
}
</script>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
    total: {
        type: Number,
        default: 0
    },
    currentPage: {
        type: Number,
        default: 0
    },
    pageSize: {
        type: Number,
        default: 0
    },
})

const emits = defineEmits(['currentPage', 'pageSize', 'update:currentPage', 'update:pageSize'])

watch(props, () => {
    total.value = props.total
    currPage.value = props.currentPage
    pageSize.value = props.pageSize
})

const total = ref(101)
const currPage = ref(11)
const btnCount = ref(5)
const pageSize = ref(10)

const pager = computed(() => {
    let pageCount = Math.ceil(total.value / 10)

    let start = currPage.value - Math.floor(btnCount.value / 2)
    if (start < 1) start = 1

    let end = start + (btnCount.value - 1)
    if (end > pageCount) {
        end = pageCount
        start = end - (btnCount.value - 1)
        if (start < 1) start = 1
    }

    let btnArr = []

    for (let i = start; i <= end; i++) {
        btnArr.push(i)
    }

    return { pageCount, start, end, btnArr }
})

const changePage = (page) => {
    if (page < 1 || page > pager.value.pageCount) return
    currPage.value = page
    emits('update:currentPage', page)
    emits('currentPage', page)
}

</script>

<style scoped lang="less">
.xtx-pagination {
    display: flex;
    justify-content: center;
    padding: 30px;

    >a {
        display: inline-block;
        padding: 5px 10px;
        border: 1px solid #e4e4e4;
        border-radius: 4px;
        margin-right: 10px;

        &:hover {
            color: @xtxColor;
        }

        &.active {
            background: @xtxColor;
            color: #fff;
            border-color: @xtxColor;
        }

        &.disabled {
            cursor: not-allowed;
            opacity: 0.4;

            &:hover {
                color: #333
            }
        }
    }

    >span {
        margin-right: 10px;
    }
}
</style>